import tkinter as tk
from ...shoudongfasong.ui_demo_toplevel import ZCAN_Demo_Toplevel
from ....utils.loggers import ic_debugger
from tkinter import messagebox
import time
from ....zlgcan.zlgcan import *
import json

from ....utils.types import TestData_Type, Uds_Request_Type, UnitTestConfig_Type, Can_TestDataStucture, UnitTestDataStructure
from ..models.modle_base import FunctestTemplate_Uds

MAX_RCV_NUM = 10


class Uds_autoUnitTab_Frame(tk.Frame):
    def __init__(self, master, masterUI, parentWin):
        super().__init__(master=master)
        self.masterUI = masterUI
        self.parentWin = parentWin

        self.autoUnitTabInit()

    def autoUnitTabInit(self):
        self.autoUnitTabDataInit()
        self.autoUnitTabViewInit()
        self.autoUnitTab_btn_function_update()
        pass

############################################################
# DOC: 自动测试库初始化#######################################
############################################################

    def autoUnitTestConfigInfo_Import(self):
        self.autoUnitTestmodelDict: dict[str, TestData_Type] = {}
        with open("config/uds_unittestConfig.json", "r", encoding="utf-8") as fp:
            self.configJson = json.loads(fp.read())

        testmodelList = self.configJson.get('data')
        for item in testmodelList:
            # 每个模块的测试配置数据
            cur = TestData_Type(**item)
            self.autoUnitTestmodelDict[cur.PosId] = cur
        pass

    def autoUnitTabDataInit(self):
        self.autoUnitTestConfigInfo_Import()

        self.autoUnitTab_UNIT_POS_LIST = []
        self.autoUnitTab_UNIT_FUN_DICT = {}
        self.autoUnitTab_UNIT_BTN_DICT = {}

        # DOC: 单元测试配置信息
        self.autoUnitTab_UNIT_TEST_CONFIG_DICT: dict[str, UnitTestConfig_Type] = {
        }
        MAX_ROW = 6
        MAX_COLUMN = 8
        for i in range(MAX_ROW):
            for j in range(MAX_COLUMN):
                position = f"{i}{j}"
                self.autoUnitTab_UNIT_POS_LIST.append(position)

        def default_autoUnit_pos_btn_click(i, j):
            return lambda: messagebox.showinfo("提示", f"autoUnit R{i}C{j}未定义")
        for pos in self.autoUnitTab_UNIT_POS_LIST:
            self.autoUnitTab_UNIT_FUN_DICT[pos] = default_autoUnit_pos_btn_click
            self.autoUnitTab_UNIT_TEST_CONFIG_DICT[pos] = UnitTestConfig_Type(pos=pos, name=f'unit_{pos}', zh_name=f'自动测试_{pos}',
                                                                              srcAddr=int(pos, 16), dstAddr=int(pos, 16)+0x80, Learmask=0xaaaaaaaa
                                                                              )

    def autoUnitTabViewInit(self):
        for i, j in self.autoUnitTab_UNIT_POS_LIST:
            self.autoUnitTab_UNIT_BTN_DICT[f"{i}{j}"] = tk.Button(
                self, text=self.autoUnitTab_UNIT_TEST_CONFIG_DICT[f'{i}{j}'].name, state=tk.DISABLED, padx=10, pady=5, command=self.autoUnitTab_UNIT_FUN_DICT[f'{i}{j}'](i, j))
            self.autoUnitTab_UNIT_BTN_DICT[f"{i}{j}"].grid(row=i, column=j)

        # 把配置文件中有定义的按钮设置为可用
        # for pos in self.autoUnitTab_UNIT_TEST_CONFIG_JSON_INFO:
            # self.autoUnitTab_UNIT_BTN_DICT[pos].configure(state=tk.NORMAL)

        # DOC 调整行列最小间距
        col_count, row_count = self.grid_size()
        for col in range(col_count):
            self.grid_columnconfigure(col, minsize=110)
        for row in range(row_count):
            self.grid_rowconfigure(row, minsize=60)

        self.autoUnitTab_btn_function_init()

    def autoUnitTab_btn_function_init(self):
        for pos, config in self.autoUnitTestmodelDict.items():
            config_dict = config.model_dump()

            def wrapper(pos):
                def inner():
                    # 此处的**关键字参数，不能直接用config_dict，否则所有的实例都是同一个，因为python中是引用传递。所以要通过self.autoUnitTestmodelDict[pos]来进行区分
                    FunctestTemplate_Uds(
                        masterUI=self.masterUI, parentWin=self,  **self.autoUnitTestmodelDict[pos].model_dump())
                return inner

            self.autoUnitTab_UNIT_BTN_DICT[pos].configure(
                state=tk.NORMAL, text=config_dict['name'], command=wrapper(pos))

    def autoUnitTab_btn_function_update(self):
        # 个别测试用例需要手动更新时，可以手工更新
        for pos in self.autoUnitTab_UNIT_POS_LIST:
            update_function = getattr(
                self, f'autoUnit_function_update_{pos}', None)
            if update_function:
                update_function()

    def autoUnit_function_update_02_sp(self):
        pos = '02'
        unitConfig = self.autoUnitTestmodelDict[pos].model_dump()

        def wrapper():
            # messagebox.showinfo('提示', 'unit02-update......')
            # DOC 此处masterUI指向自己，parentWin也是自己，所以两者是同一个指向对象
            # 如果FunctestTemplate不是通过主窗口调用，而是通过其他Toplevel调用，那么两者可能是不相同的
            FunctestTemplate_Uds(masterUI=self.masterUI,
                                 parentWin=self, **unitConfig)
        self.autoUnitTab_UNIT_BTN_DICT[pos].configure(
            state=tk.NORMAL, text=unitConfig['name'], command=wrapper)


############################################################
# DOC: 自动测试库初始化#######################################
############################################################
